# --*-- coding: utf-8 -*-

import numpy as np
import cv2
import sys

def polar(I, center, r, theta=(0, 360), rstep=1.0, thetastep=360.0/(180*8)):
    """
    # I : Image
    # center: center corner
    # r : (min, max)
    # theta : (min, max)
    """
    minr, maxr = r
    mintheta, maxtheta = theta

    cx, cy = center

    H = int((maxr - minr)/rstep) + 1
    W = int((maxtheta - mintheta)/thetastep) + 1
    O = 125 * np.ones((H, W), I.dtype)

    r = np.linspace(minr, maxr, H)
    r = np.tile(r, (W, 1))
    r = np.transpose(r)

    theta = np.linspace(mintheta, maxtheta, W)
    theta = np.tile(theta, (H, 1))
    x, y = cv2.polarToCart(r, theta, angleInDegrees=True)

    for i in range(H):
        for j in range(W):
            px = int(round(x[i][j]) + cx)
            py = int(round(y[i][j]) + cy)
            if (px >= 0 and px <= W - 1) and (py >= 0 and py <= H-1):
                O[i][j] = I[py][px]

    return O

def original_func(ImageData):
    h, w = ImageData.shape[:2]
    print("image: ", w, ", ", h)
    cx, cy = 208, 203
    cv2.circle(ImageData, (int(cx), int(cy)), 200, (255.0, 0, 0), 3)

    O = polar(ImageData, (cx, cy), (100, 150))

    O = cv2.flip(O, 0)
    cv2.imshow("I", ImageData)
    cv2.imshow("O", O)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def use_cv(ImageData):
    # dst = cv2.linearPolar(ImageData, (200, 203), 300, cv2.INTER_LINEAR)
    dst = cv2.logPolar(ImageData, (200, 203), 10, cv2.WARP_FILL_OUTLIERS)
    cv2.imshow("src", ImageData)
    cv2.imshow("dst", dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    if len(sys.argv) > 1:
        I = cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE)
    else:
        print("Usage: xxx file")
        exit(0)

    # original_func(I)
    use_cv(I)